package com.zdy.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.example.networklibrary.model.QuestionsModel;
import com.zdy.showgoods.R;

import java.util.ArrayList;
import java.util.List;

public class PickerAdapter extends RecyclerView.Adapter<PickerAdapter.ItemHolder> {
    private SparseBooleanArray mCheckStates = new SparseBooleanArray();
    private ArrayList<QuestionsModel> selItems = new ArrayList<>();
    private List<QuestionsModel> mList;
    private Context context;

    public PickerAdapter(List<QuestionsModel> list, Context context) {
        mList = list;
        this.context = context;
    }

    @Override
    public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.item_feedback, null, false);
        return new ItemHolder(v);
    }

    @Override
    public void onBindViewHolder(ItemHolder holder, int position) {
        holder.cbx.setTag(position);
        holder.cbx.setText(mList.get(position).getContent());
        holder.cbx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int pos = (int) buttonView.getTag();
                if (mCheckStates.get(pos, false) == isChecked) return;
                if (isChecked) {
                    mCheckStates.put(pos, true);
                } else {
                    mCheckStates.delete(pos);
                }
            }
        });
    }

    public String getSelectItems() {
        String ids = "";
        for (int i = 0; i < mCheckStates.size(); i++) {
            ids = "," + mList.get(mCheckStates.keyAt(i)).getId() + ids;
        }
        return ids.substring(1);
    }

    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }

    static class ItemHolder extends RecyclerView.ViewHolder {
        CheckBox cbx;

        public ItemHolder(View itemView) {
            super(itemView);
            cbx = (CheckBox) itemView.findViewById(R.id.feedback_check);
        }
    }
}